/**
 * 详情对话框
 */
var WechatUserInfoDlg = {
    data: {
        openId:""
        ,wechatNickName:""
        ,accountName:""
        ,userNo:""
        ,createTime:""
        ,remark:""
        ,phone:""
        ,userName:""
        ,email:""
        ,sex:""
        ,birthDay:""
        ,age:""
        ,userId:""
        ,deviceInfo:""
        ,deviceId:""
    }
};
var cardTypeIds = "";
var areaNames="";
layui.use(['form', 'ax','laydate','admin','citypicker'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var cityPicker = layui.citypicker;
    var admin = layui.admin;
    // 让当前iframe弹层高度适应
    admin.iframeAuto();

    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/wechatUser/detail/" + Feng.getUrlParam("id"));
    var result = ajax.start();
    var currentPicker = new cityPicker("#area", {
        provincename:"广东省",
        cityname:"东莞市",
        districtname: "寮步镇",
        level: '3',// 级别
        finish:function(){
            console.log("选择结束："+$("#area").val());
            areaNextChange();
        }
    });
    var areaData = result.data.area;
    var areaDatas = areaData.split(",");
    console.log("区域："+areaDatas[0]+","+areaDatas.length);
    currentPicker.setValue(areaDatas[0]);

    form.val('wechatUserForm', result.data);
    $("#birthDay").val(result.data.birthDay.substring(0,10));
    $("#area").val(areaDatas[0]);
    if(areaDatas.length>1){
        $("#areaNext").html("<option value='"+areaDatas[1]+"'>"+areaDatas[1]+"</option>");

    }
    var userBinList = result.data.userBinList;
    var wasteStationId = -1;
    if(userBinList.length>0){
        wasteStationId = userBinList[0].wasteStationId;
        $("#wasteStationId").val(wasteStationId);
        for(var i=0;i<userBinList.length;i++){
            $("[name=typeId]:eq("+i+")").val(userBinList[i].wasteTypeId);
            $("[name=cardNo]:eq("+i+")").val(userBinList[i].cardNo);
            cardTypeIds+=userBinList[i].wasteTypeId+";";
        }
    }
    form.render("select");
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var validation = new Validation($("#wechatUserForm")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            var ajax = new $ax(Feng.ctxPath + "/wechatUser/editItem", function (data) {
                if(data.success){
                    Feng.success("更新成功！");
                    //传给上个页面，刷新table用
                    admin.putTempData('formOk', true);

                    //关掉对话框
                    admin.closeThisDialog();
                }else{
                    Feng.error("更新失败！"+data.message);
                }

            }, function (data) {
                Feng.error("更新失败！" + data.responseJSON.message)
            });
            var typeIdList = $("[name=typeId]");
            var typeIds = "";
            for(var i=0;i<typeIdList.length;i++){
                typeIds+=typeIdList[i].value+",";
            }
            $("#typeIds").val(typeIds);
            console.log("类别："+typeIds);
            var cardNoList = $("[name=cardNo]");
            var cardNos = "";
            for(var i=0;i<cardNoList.length;i++){
                if(cardNoList[i].value!="" && cardNos.indexOf(cardNoList[i].value)>=0){
                    Feng.error("卡号："+cardNoList[i].value+"，重复");
                    return false;
                }
                cardNos+=cardNoList[i].value+",";
            }
            $("#cardNos").val(cardNos);
            console.log("卡号："+cardNos);
            ajax.set(data.field);
            ajax.set("typeIds",typeIds);
            ajax.set("cardNos",cardNos);
            ajax.start();
        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;

    });
    form.on("select(wasteType)",function(data){
        console.log("类别："+data.value);
        console.log("已选类别："+cardTypeIds);

        if(cardTypeIds.indexOf(data.value)>=0){
            Feng.error("该类别已经选择！");
        }else{
            cardTypeIds = "";
            $("[name=typeId]").each(function(){
                cardTypeIds+=this.value+";";
            });
        }

    })

    var areaNextChange = function(){
        console.log("点击所在村：");
        var curAreaName = $("#area").val();
        if(curAreaName!=areaNames){


            var that = $("#areaNext")[0];
            $.getJSON(Feng.ctxPath+"/region/searchReturnCode?params="+$("#area").val()+"&r="+Math.random(),function(areaMap){
                $(that).empty();
                var isFirst = true;
                var areaCode = $("#areaCode").val();
                for(area in areaMap){
                    if(isFirst) {
                        $("#areaCode").val(area);
                        isFirst = false;
                    }
                    $(that).html($(that).html()+"<option value='"+area+"'>"+areaMap[area]+"</option>");
                }
                if(areaCode!="") {
                    $("#areaNext").val(areaCode);
                    listWasteStation(areaCode);
                }
                form.render("select");
                layer.closeAll();
                $("#areaNext").parent().find(":text").click(function(){
                    areaNextChange();
                })
            });
            areaNames = curAreaName;
        }
    }
    $("#areaNext").parent().find(":text").click(function(){
        layer.msg('加载村数据中', {
            icon: 16
            ,shade: 0.01
        });
        console.log("当前区域："+areaNames);
        areaNextChange();
    })
    if($("#area").val()!=""){
        $("#areaNext").parent().find(":text").click();
    }

    $(".city-picker-span .select-item").click(function(event){
        console.log("内容变化："+$("#area").val())
    });
    var listWasteStation = function(areaCode){
        $.getJSON(Feng.ctxPath+"/wasteStation/searchByArea",{"areaCode":areaCode},function(wasteStationList){
            $("#wasteStationId").empty();
            var wasteStationHtml = "";
            for(var i=0;i<wasteStationList.length;i++){
                wasteStationHtml+="<option value='"+wasteStationList[i].id+"'>"+wasteStationList[i].stationName+"</option>";
            }
            $("#wasteStationId").html(wasteStationHtml);
            form.render("select");
        });
    }
    form.on("select(areaFilter)",function (data) {
        console.table(data);
        $("#areaCode").val(data.value);
        listWasteStation(data.value);
    })

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + "/wechatUser";
    });
    var laydate = layui.laydate;
    lay('.datetime-input').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: 'date'
        });
    });
});